import React from 'react'
import Layout from './Layout'
import { Row, Col, Space, Button, Empty } from 'antd'
import FiterByCatogry from './FiterByCatogry'
import FilterByPrice from './FilterByPrice'
import { useState, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { filter_product } from '../../store/actions/filter'
import ProductItem from './ProductItem'

function Shop() {
	const dispatch = useDispatch()
	// 声明一个存储数据的state, filters里面包含categry和price
	const [filters, setFilters] = useState({categry:[], price:[]})
	const [skip, setSkip] = useState(0)

	useEffect(() => {
		setSkip(0)
	}, [filters])

	useEffect(() => {
		dispatch(filter_product({ filters, skip }))
	}, [filters, skip]) // eslint-disable-line react-hooks/exhaustive-deps

	const { size, data } = useSelector(state => state.filter)

	const loadMore = () =>{
		setSkip(skip + 4)
	} 

	return (
		<>
			<Layout title="拉勾严选商城列表" subTitle="挑选你喜欢的商品吧">
				<Row gutter={[16, 16]}>
					<Col span={4}>
						<Space direction="vertical" size="middle">
							<FiterByCatogry handleFilter={filter => {
								// setFilters 对state的数据进行修改并重新赋予新值
								// ...filters 结构当前存储在filters的categry,和price数组
								// filter 对filters的categry属性重新赋值
								setFilters({...filters, categry:filter})
							}}/>
							<FilterByPrice handleFilter={filter => {
								setFilters({...filters, price:filter})
							}}/>
						</Space>
					</Col>
					<Col span={20}>
						<Row gutter={[16,16]}>
							{
								data.map(item=>
									(
										<Col key={item._id} span={6}>
											<ProductItem product={item}/>
										</Col>
									)
								)
							}
						</Row>
						<Row>
							{
								size >= 4 ? (
									<Button onClick={loadMore} type="primary" style={{marginTop: '15px'}}>加载更多</Button>
								) : (
									<Empty />
								)
							}
						</Row>
					</Col>
				</Row>
			</Layout>
		</>
	)
}

export default Shop
